const express = require('express')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const UserRouter = require('./routers/User')
const ChatRouter = require('./routers/Chat')
const model = require('./model')
const Chat = model.getModel('chat')
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const path = require('path')
const ReactDomServer = require('react-dom/server')

//function App(){
//    return (
//        <div>
//            <h1>hello world</h1>
//        </div>
//    )
//}

io.on('connection', (socket) => {
    socket.on('sendMsg', (data) => {
        const { from, to, content } = data
        Chat.create({...data, time: new Date().getTime(), group: [from,to].sort().join('_') }, (err, doc) => {
            let result = {}
            if(err) result = {code: 1, messages: [], from, to}
            else result = {code: 0, messages: [doc._doc], from, to}
            io.emit('receiveMsg', result)
        })
    })
})

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

app.use(cookieParser())

app.use('/user', UserRouter)
app.use('/chat', ChatRouter)

app.use('/', express.static(path.join(__dirname, '../build')))

//处理404
app.use(function (req, res) {
    res.sendFile(path.join(__dirname, '../build/index.html'))
})
// 配置错误处理中间件
app.use(function (err, req, res, next) {
    res.status(500).json({ code: 1, message: '系统繁忙，请稍后重试'})
})

server.listen(8000, () => {
    console.log('server started at port 8000')
})